package yazan.com.pdacollector_android.presenter;

import android.os.Handler;
import android.os.Looper;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;

import org.greenrobot.greendao.query.QueryBuilder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import yazan.com.pdacollector_android.PDAApplication;
import yazan.com.pdacollector_android.base.Presenter;
import yazan.com.pdacollector_android.model.Goods;
import yazan.com.pdacollector_android.model.GoodsDao;
import yazan.com.pdacollector_android.model.OrderBrowser;
import yazan.com.pdacollector_android.model.OrderInfo;
import yazan.com.pdacollector_android.model.OrderInfoDao;
import yazan.com.pdacollector_android.network.Api;
import yazan.com.pdacollector_android.network.RetrofitManager;
import yazan.com.pdacollector_android.utils.PDAGlobal;

public class OrderPresenter extends Presenter {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void downLoadOrderInfo(String uniqueID, String userName, int pageIndex, final PresenterListener<OrderInfo> presenterListener) {
        Api api = null;
        try {
            api = RetrofitManager.getInstance()
                    .setBaseUrl(PDAGlobal.baseUrl)
                    .build(Api.class);
        } catch (Exception e) {
            ToastUtils.showShort(e.getMessage());
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("PageSize", 0);
        params.put("PageIndex", pageIndex);
        params.put("ForderId", uniqueID);
        params.put("ForderUser", userName);

        api.getOrderInfo(params).enqueue(new Callback<OrderInfo>() {
            @Override
            public void onResponse(Call<OrderInfo> call, Response<OrderInfo> response) {
                if (presenterListener == null) {
                    return;
                }
                if (response.isSuccessful()) {
                    presenterListener.onSuccess(response.body());
                } else {
                    presenterListener.onError(response.code() + "");
                }
            }

            @Override
            public void onFailure(Call<OrderInfo> call, Throwable t) {
                if (presenterListener == null) {
                    return;
                }
                presenterListener.onError(t.getMessage());
            }
        });

    }

    public static void submitOrderInfo(List<Goods> goodsList, String userName, final PresenterListener<HashMap> presenterListener) {
        Api api = null;
        try {
            api = RetrofitManager.getInstance()
                    .setBaseUrl(PDAGlobal.baseUrl)
                    .build(Api.class);
        } catch (Exception e) {
            ToastUtils.showShort(e.getMessage());
            return;
        }

        HashMap<String, Object> params = new HashMap<>();
        params.put("Forder_id", goodsList.get(0).getForder_id());
        params.put("Forder_user", userName);
        params.put("Fexa_date", TimeUtils.date2String(new Date(), dateFormat));
        ArrayList<HashMap<String, String>> orderList = new ArrayList();
        for (Goods goods : goodsList) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Findex", goods.getFIndex() + "");
            item.put("Fgoods_sn", goods.getFgoods_sn());
            item.put("Fgoods_codes", goods.getFgoods_codes() == null ? "" : goods.getFgoods_codes());
            orderList.add(item);
        }
        params.put("OrderList", orderList);
        api.postOrder(params).enqueue(new Callback<HashMap>() {
            @Override
            public void onResponse(Call<HashMap> call, Response<HashMap> response) {
                if (presenterListener == null) {
                    return;
                }
                if (response.isSuccessful()) {
                    presenterListener.onSuccess(response.body());
                } else {
                    presenterListener.onError(response.code() + "");
                }
            }

            @Override
            public void onFailure(Call<HashMap> call, Throwable t) {
                if (presenterListener == null) {
                    return;
                }
                presenterListener.onError(t.getMessage());
            }
        });

    }

    public static void getOrderBrowser(String Forder_statime,
                                       String Forder_endtime,
                                       String Forder_user,
                                       int Forder_status,
                                       int PageIndex,
                                       Long Fordersn,
                                       final PresenterListener<OrderBrowser> presenterListener) {
        Api api = null;
        try {
            api = RetrofitManager.getInstance()
                    .setBaseUrl(PDAGlobal.baseUrl)
                    .build(Api.class);
        } catch (Exception e) {
            ToastUtils.showShort(e.getMessage());
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("Forder_statime", Forder_statime);
        params.put("Forder_endtime", Forder_endtime);
        params.put("Forder_user", Forder_user);
        params.put("Forder_status", Forder_status);
        params.put("PageSize", 0);
        params.put("PageIndex", PageIndex);
        if (Fordersn != null) {
            params.put("Fordersn", Fordersn);
        }
        api.getOrderBrowser(params).enqueue(new Callback<OrderBrowser>() {
            @Override
            public void onResponse(Call<OrderBrowser> call, Response<OrderBrowser> response) {
                if (presenterListener == null) {
                    return;
                }
                if (response.isSuccessful()) {
                    presenterListener.onSuccess(response.body());
                } else {
                    presenterListener.onError(response.code() + "");
                }
            }

            @Override
            public void onFailure(Call<OrderBrowser> call, Throwable t) {
                if (presenterListener == null) {
                    return;
                }
                presenterListener.onError(t.getMessage());
            }
        });
    }


    public static void insertOrderInfo(final OrderInfo orderInfo, final PresenterListener<Boolean> presenterListener) {

        PDAApplication.getInstance().getDaoSession().startAsyncSession().runInTx(new Runnable() {
            @Override
            public void run() {
                OrderInfoDao orderInfoDao = PDAApplication.getInstance().getDaoSession().getOrderInfoDao();
                GoodsDao goodsDao = PDAApplication.getInstance().getDaoSession().getGoodsDao();
                orderInfoDao.insertOrReplace(orderInfo);
                goodsDao.insertOrReplaceInTx(orderInfo.getData());

                if (presenterListener == null) {
                    return;
                }
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        presenterListener.onSuccess(true);
                    }
                });
            }
        });
    }

    public static void deleteOrderInfo(final long Forder_id, final List<Goods> goodsList, final PresenterListener<Boolean> presenterListener) {
        PDAApplication.getInstance().getDaoSession().startAsyncSession().runInTx(new Runnable() {
            @Override
            public void run() {
                OrderInfoDao dao = PDAApplication.getInstance().getDaoSession().getOrderInfoDao();
                dao.deleteByKey(Forder_id);
                if (goodsList != null && goodsList.size() > 0) {
                    GoodsDao goodsDao = PDAApplication.getInstance().getDaoSession().getGoodsDao();
                    goodsDao.deleteInTx(goodsList);
                }

                if (presenterListener == null) {
                    return;
                }
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        presenterListener.onSuccess(true);
                    }
                });
            }
        });
    }


    public static void searchOrderInfo(final String Forder_id, final PresenterListener<OrderInfo> presenterListener) {
        PDAApplication.getInstance().getDaoSession().startAsyncSession().runInTx(new Runnable() {
            @Override
            public void run() {
                OrderInfoDao dao = PDAApplication.getInstance().getDaoSession().getOrderInfoDao();
                PDAApplication.getInstance().getDaoSession().clear();
                final List<OrderInfo> orderInfoList = dao.queryBuilder().where(OrderInfoDao.Properties.Forder_id.eq(Forder_id)).build()
                        .list();
                if (presenterListener == null) {
                    return;
                }
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        OrderInfo result = null;
                        if (orderInfoList != null && orderInfoList.size() > 0) {
                            result = orderInfoList.get(0);
                        }
                        presenterListener.onSuccess(result);
                    }
                });
            }
        });
    }

    public static void searchOrderInfo(final String beginTime,
                                       final String endTime,
                                       final String uniqueCode,
                                       final PresenterListener<List<OrderInfo>> presenterListener) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        final Date begin = TimeUtils.string2Date(beginTime, dateFormat);
        final Date end = TimeUtils.getDate(endTime, dateFormat, 1, TimeConstants.DAY);


        PDAApplication.getInstance().getDaoSession().startAsyncSession().runInTx(new Runnable() {
            @Override
            public void run() {
                List<OrderInfo> temp;
                OrderInfoDao dao = PDAApplication.getInstance().getDaoSession().getOrderInfoDao();
                QueryBuilder<OrderInfo> queryBuilder = dao.queryBuilder();
                if (StringUtils.isTrimEmpty(uniqueCode)) {
                    temp = queryBuilder.where(OrderInfoDao.Properties.Fexa_date.between(begin,
                            end)).build()
                            .list();
                } else {
                    temp = queryBuilder.where(OrderInfoDao.Properties.Fexa_date.between(begin,
                            end), OrderInfoDao.Properties.Forder_id.eq(uniqueCode)).build()
                            .list();
                }
                final List<OrderInfo> orderInfoList = temp;
                if (presenterListener == null) {
                    return;
                }
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        presenterListener.onSuccess(orderInfoList);
                    }
                });
            }
        });

    }
}
